import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import db from '../../utils/localstorage'

export type UserInfo = Partial<{
  userName: string
  avatar: string
  email: string
  sex: string
  nickName: string
  phonenumber: string
  remark: string

  userId: string | number
  admin: boolean
  loginDate: string
  loginIp: string
  status: string
}>

export interface UserState {
  info: UserInfo
  permissions: string[]
  roles: string[]
  token: string
}

export const UserSlice = createSlice({
  name: 'user',

  initialState: <UserState>{
    info: db.get('user', {}),
    permissions: db.get('permissions', []),
    roles: db.get('roles', []),
    token: db.get('token', '')
  },

  reducers: {
    setInfo(state: UserState, action: PayloadAction<UserInfo>) {
      console.log(action)
      db.set('user', action.payload)
      state.info = action.payload
    },

    setToken(state: UserState, action: PayloadAction<string>) {
      db.set('token', action.payload)
      state.token = action.payload
    }
  },
})

export default UserSlice.reducer
